import { fileURLToPath } from 'url';
import path from 'path';
import fs from 'fs';
import yaml from 'yaml';
import { CronJob } from 'cron'; 
import { createLogger } from './Logger.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const CONFIG_PATH = path.resolve(__dirname, '../config/timeconfig.yaml');

let taskGroups = {
    "皮皮的定时器": [],
};

// 创建日志实例
const logger = createLogger('皮皮的定时器');

function convertToCronExpression(timeValue) {
    if (typeof timeValue === 'number') {
        return `*/${timeValue} * * * *`; 
    } else if (typeof timeValue === 'string' && timeValue.startsWith('s')) {
        const hours = parseInt(timeValue.slice(1)); 
        return `0 */${hours} * * *`;
    } else {
        throw new Error('配置时间值格式错误');
    }
}

// 加载配置文件
function loadTimeConfig() {
    if (fs.existsSync(CONFIG_PATH)) {
        const content = fs.readFileSync(CONFIG_PATH, 'utf8');
        const config = yaml.parse(content); 

    //    logger.info(`加载配置文件：${JSON.stringify(config)}`);
    //    logger.info('加载成功');
        return config;
    } else {
        const defaultConfig = {
            "PippiStatusPlugin": 5,     //  1为分钟：弹幕姬
            "ServerStatusPlugin": 's1',  // s1为小时：mc服务器
        };
        saveTimeConfig(defaultConfig);
    //    logger.info(`配置文件不存在，已创建默认配置：${JSON.stringify(defaultConfig)}`);
        return defaultConfig;
    }
}

function saveTimeConfig(config) {
    const yamlContent = yaml.stringify(config); 
    fs.writeFileSync(CONFIG_PATH, yamlContent, 'utf8');
//    logger.info(`已保存配置到：${CONFIG_PATH}`);
}

function addTaskToGroup(taskName, taskFunction, cronExpression) {
    if (!taskGroups["皮皮的定时器"]) {
        taskGroups["皮皮的定时器"] = [];
    }

    const existingTask = taskGroups["皮皮的定时器"].find(t => t.name === taskName);
    if (existingTask) {
    //    logger.info(`任务 "${taskName}" 已存在，禁止重复添加`);
        return;  // 如果任务已存在，则不添加
    }

    const job = new CronJob(cronExpression, taskFunction, null, true, 'Asia/Shanghai');
    taskGroups["皮皮的定时器"].push({
        name: taskName,
        cronJob: job,
    });

//    logger.info(`已将任务 "${taskName}" 添加到任务组 "皮皮的定时器"`);
}

// 停止任务
function stopTaskFromGroup(taskName) {
    const group = taskGroups["皮皮的定时器"];
    const task = group.find(t => t.name === taskName);
    if (task) {
        task.cronJob.stop();
        taskGroups["皮皮的定时器"] = group.filter(t => t.name !== taskName);
    }
}

function getTaskGroup(groupName) {
    return taskGroups[groupName] || [];
}

// 延时统计任务数量
setTimeout(() => {
    const taskCount = taskGroups["皮皮的定时器"].length;
    logger.info(`
****************************************
*        一共启动了 ${taskCount} 个任务        *
****************************************
    `);
}, 10000); // 延时3秒执行


export { loadTimeConfig, saveTimeConfig, addTaskToGroup, stopTaskFromGroup, getTaskGroup };